﻿#region <<版本注释>>
/*---------------------------------------------------------------------
* 项目名称：DoubleDB
* 项目描述：
* 类 名 称：DataConvert
* 类 描 述：
* 所在的域：DESKTOP-6CB1TV7
* 命名空间：DoubleDB
* 机器名称：DESKTOP-6CB1TV7
* CLR 版本：4.0.30319.42000
* 作    者：wky
* 创建时间：2023/01/04 09:45:39
* 更新时间：2023/01/04 09:45:39
* 版 本 号:V1.0.0
***********************************************************************
* Copyright @ wky 2023. All rights reserved.
***********************************************************************
//-------------------------------------------------------------------*/
#endregion

using DoubleDB.IotNiRenDataStruct;
using DoubleDB.NiRenDataStruct;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DoubleDB
{
    public class DataConvert
    {
        Timing timing = null;

        public const string dtFormatStr = "yyyy-MM-dd HH:mm:ss";

        public static DateTime DateTimeConvert(string dtStr) {
            return DateTime.ParseExact(dtStr, dtFormatStr, System.Globalization.CultureInfo.CurrentCulture);
        }

        public static DateTime getUniversalDateTime() {
            return DateTimeConvert("2006-01-01 00:00:00");
        }

        public static long calcDateTime2Msec(DateTime newDt,DateTime oldDt) {
            TimeSpan ts = newDt - oldDt;
            return (long)ts.TotalMilliseconds;
        }

        public DataConvert(Timing timing) {
            this.timing = timing;
        }

        public int devConvert() {
            if (timing.Dev == null) return 0;
            int result = 0;
            bool ret = int.TryParse(timing.Dev, out result);
            if(ret) return result;
            return 0;
        }

        /// <summary>
        /// 定时任务名，由于旧库中没有此信息，只能通过设备名+时间戳组成，
        /// 精确到毫秒，
        /// 如果找不到设备，即只有 时间戳
        /// </summary>
        /// <returns></returns>
        public string timerName() {

            //ToUniversalTime()将当前DateTime对象的值转换为世界标准时间(UTC)
            TimeSpan mTimeSpan = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0);
            //得到精确到毫秒的时间戳（长度10位）
            long time = (long)mTimeSpan.TotalMilliseconds;
            //Console.WriteLine("demo1:" + time);

            var devs = DataCtrl.devs.Where(o => o.Id == this.devConvert()).ToList();
            if (devs.Count == 0) return time.ToString();
            return devs[0].DevName + time.ToString();
        }

        /// <summary>
        /// 结束时间转换
        /// </summary>
        /// <returns></returns>
        public DateTime etimConvert() {
            if(timing.Etim == null || timing.Etim.Equals("") || timing.Etim.Equals("请选择截止时间")) return getUniversalDateTime();
            return DateTimeConvert(timing.Etim);
        }

        /// <summary>
        /// 使能与禁止 状态？
        /// </summary>
        /// <returns></returns>
        public int staConvert() {
            if (timing.Sta == null) return 0;
            if (timing.TbSta != null && !timing.TbSta.Equals("")) {
                if (timing.TbSta.Contains("删除")) return 0;
            }
            return timing.Sta.Equals("true") ? 1 : 0;
        }

        /// <summary>
        /// 工作模式
        /// </summary>
        /// <returns></returns>
        public int workMode() {
            if (timing.Wed == null) return 0;
            if (timing.Wed.Contains("单次"))
                return 6;
            return 4;
        }

        public int wedConvert() {
            if (timing.Wed == null) return 0;
            if (timing.Wed.Contains("单次")) {
                return 0x0000;
            } else {
                int week = 0;

                //星期一[|br|]星期二[|br|]星期三[|br|]星期四[|br|]星期五[|br|]星期六[|br|]星期日[|br|]
                if (timing.Wed.Contains("星期日"))
                    week |= 0x0001;

                if (timing.Wed.Contains("星期一"))
                    week |= 0x0002;

                if (timing.Wed.Contains("星期二"))
                    week |= 0x0004;

                if (timing.Wed.Contains("星期三"))
                    week |= 0x0008;

                if (timing.Wed.Contains("星期四"))
                    week |= 0x0010;

                if (timing.Wed.Contains("星期五"))
                    week |= 0x0020;

                if (timing.Wed.Contains("星期六"))
                    week |= 0x0040;

                return week;
            }
        }

        /// <summary>
        /// 执行时间转换
        /// </summary>
        /// <returns></returns>
        public DateTime timConvert()
        {
            if (timing.Tim == null || timing.Tim.Equals("")) return getUniversalDateTime();
            if (timing.Tim.Contains("时")) {
                string[] strs1 = timing.Tim.Split(new string[] { "时", "分", "秒" }, StringSplitOptions.None);
                int h = int.Parse(strs1[0]);
                int m = int.Parse(strs1[1]);
                int s = int.Parse(strs1[2]);
                string str = "2006-01-01 " + (h > 9 ? "" : "0") + h.ToString() + ":" + (m > 9 ? "" : "0") + m.ToString() + ":" + (s > 9 ? "" : "0") + s.ToString();
                return DateTimeConvert(str);
            } else {
                return DateTimeConvert(timing.Tim);
            }
        }

        /// <summary>
        /// 旧库的备注为动作，这里不需要
        /// </summary>
        /// <returns></returns>
        public int orderConvert() {
            if (timing.Order == null || timing.Order.Equals("")) return 0;
            return 0;
        }

        /// <summary>
        /// 更新时间
        /// </summary>
        /// <returns></returns>
        public DateTime utimConvert() {
            if (timing.Utim == null || timing.Utim.Equals("")) return DateTime.Now;// getUniversalDateTime();
            return DateTimeConvert(timing.Utim);
        }

        /// <summary>
        /// 长期有效标志
        /// </summary>
        /// <returns></returns>
        public bool longTimeConvert() {
            if (timing.LongTime == null || timing.LongTime.Equals("")) return false;
            return timing.LongTime.Equals("true");
        }

        /// <summary>
        /// 开始时间
        /// </summary>
        /// <returns></returns>
        public DateTime stimConvert() {
            if (timing.Stim == null || timing.Stim.Equals("") || timing.Stim.Equals("请选择开始时间")) return getUniversalDateTime();
            return DateTimeConvert(timing.Stim);
        }

        public int tbConvert() {
            if (timing.Tb == null || timing.Tb.Equals("")) return 0;
            if (timing.Tb.Contains("未同步")) return 0;
            return 3;
        }

        /// <summary>
        /// 删除即为3(DelSync=3，在java代码中有定义)，其他均为0
        /// </summary>
        /// <returns></returns>
        public int getSyncState()
        {
            if (timing.TbSta == null || timing.TbSta.Equals("")) return 0;
            if (timing.TbSta.Contains("删除")) return 3;
            return 0;
        }

        public List<SysTaskCtrlEvent> dat1Convert() {
            List<SysTaskCtrlEvent> events = new List<SysTaskCtrlEvent>();
            if (timing.Dat1 == null || timing.Dat1.Equals("")) return events;
            //开-true-22708[|br|]开-false-22709[|br|]
            //点动开-0时0分10秒-true-29677[|br|]
            string[] strs1 = timing.Dat1.Split(new string[] { "[|br|]" },StringSplitOptions.None);
            foreach(string str in strs1) {
                if (str == null || str.Equals("")) continue;
                string[] strs2 = str.Split('-');
                if (strs2.Length < 3) continue;
                if (strs2[1].Contains("false")) continue;
                int actionType = getActionType(strs2[0]);

                if (actionType == 0) continue;

                int flusthTime = -1;
                if (actionType > 2)
                    flusthTime = getFlushTime(strs2[1]);

                int nodeId = 0;//
                if (strs2.Length == 3) {
                    nodeId = int.Parse(strs2[2]);
                } else {
                    nodeId = int.Parse(strs2[3]);
                }
                //查旧库的do数据
                var dos = DataCtrl.dos.Where(o => o.Id == nodeId).ToList();
                if (dos.Count == 0) continue;
                //根据旧库do的uid与通道号查新库的do节点数据
                var nodes = DataCtrl.nodes.Where(o => o.DevSn == dos[0].Uid && o.NodeCh==dos[0].No && o.NodeType==0).ToList();
                if (nodes.Count == 0) continue;
                //根据uid查找do节点数据对应的设备信息
                var devs = DataCtrl.devs.Where(o => o.DevSn == nodes[0].DevSn).ToList();
                if (devs.Count == 0) continue;
                //如果节点的通道号大于设备的do数量，即不能使用
                if (nodes[0].NodeCh > devs[0].DoNum) continue;

                SysTaskCtrlEvent taskEvent = new SysTaskCtrlEvent() {
                    TaskType = 0,
                    IsEnabled = 1,
                    AreaIds = "1",
                    AreaNames = "默认区域",
                    DevIds = devs[0].Id.ToString(),
                    DevNames = devs[0].DevName,
                    NodeIds = nodes[0].Id.ToString(),
                    NodeNames = nodes[0].NodeName,
                    ActionType = actionType,
                    FlushTime = flusthTime,
                    CloseTime = -1,
                    LoopNum = -1,
                    DlyTime = -1,
                    SyncState = this.tbConvert(),
                    CreateDate = DateTime.Now,
                    ModifyDate = DateTime.Now,
                };

                events.Add(taskEvent);
            }
            return events;
        }

        public int getActionType(string actionTypeStr) {
            if (actionTypeStr == null || actionTypeStr.Equals("")) return 0;
            if (actionTypeStr.Equals("开")) return 1;
            if (actionTypeStr.Equals("关")) return 2;
            if (actionTypeStr.Equals("点动开")) return 3;
            return 4;
        }

        public int getFlushTime(string actionTime) {
            if (actionTime == null || actionTime.Equals("")) return 0;
            string[] strs1 = actionTime.Split(new string[] { "时","分","秒"},StringSplitOptions.None);
            int h = int.Parse(strs1[0]);
            int m = int.Parse(strs1[1]);
            int s = int.Parse(strs1[2]);
            return (h * 60 * 60 + m * 60 + s);
        }



    }
}
